package com.vhall.component.plugin.core.service;

import com.alibaba.fastjson.JSON;
import com.vhall.component.entity.account.vo.AccountInfo;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author rui.zhou
 * @date 2021/4/26 16:20
 */
@Slf4j
@Service
public class TokenService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 拿当前用户登录信息
     *
     * @param token
     * @return
     */
    public AccountInfo getAccount(String token) {
        AccountInfo account = null;

        if (StringUtils.isBlank(token)) {
            throw new BusinessException(BizErrorCode.AUTH_LOGIN_NEEDS);
        }
        try {
            String userJson = redisTemplate.opsForValue().get(RedisKey.AUTH_TOKEN + token);
            if (StringUtils.isBlank(userJson)) {
                throw new BusinessException(BizErrorCode.AUTH_LOGIN_NEEDS);
            }
            String str = JSON.parse(userJson).toString();
            account = JSON.parseObject(str, AccountInfo.class);
        } catch (Exception e) {
            log.error("获取用户信息失败 param:" + token, e);
            throw new BusinessException(BizErrorCode.AUTH_LOGIN_NEEDS);
        }
        return account;
    }


    public AccountInfo getAccount() {
        AccountInfo account = new AccountInfo();
        account.setAccountId(193604);
        account.setPhone("17783641974");
        account.setUsername("lushunli");
        account.setToken("274e837eb5b0030c");
        account.setStatus(0);
        account.setAccountType(1);
        return account;
    }
}
